package com.fengxu.gamescript.ui.main

import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.WindowManager
import android.widget.ImageButton
import androidx.viewpager.widget.ViewPager
import com.fengxu.gamescript.R
import com.fengxu.gamescript.ui.setting.SettingDialog
import com.fengxu.gamescript.data.Conf
import com.fengxu.gamescript.data.GlobalData
import com.fengxu.gamescript.service.AutoAccessibilityService
import com.fengxu.gamescript.service.SafeService
import com.fengxu.gamescript.ui.article.ArticleActivity
import com.fengxu.gamescript.ui.base.BaseActivity
import com.fengxu.gamescript.ui.float.MainFloatViewWrapper
import com.fengxu.gamescript.ui.log.LoggerActivity
import com.fengxu.gamescript.ui.main.mode.TabFragmentAdapter
import com.fengxu.gamescript.ui.signin.SignInActivity
import com.fengxu.gamescript.util.CommonUtils
import com.xuexiang.xui.widget.tabbar.TabSegment
import org.jetbrains.anko.sdk27.coroutines.onClick
import java.io.File
import kotlin.properties.Delegates

class MainActivity : BaseActivity() {

    // viewPage
    private val viewPage: ViewPager by lazy {
        findViewById<ViewPager>(R.id.viewPage)
    }

    // 设置项窗体
    private lateinit var settingDialog: SettingDialog

    // 存储所有注册的tab选择事件
    val tabSelectChangeEvents = mutableListOf<(Int)->Unit>()

    // 监听用户点击键位事件 int表示keyEvent.键码
    val keyDownListener = mutableListOf<(Int)->Boolean>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        backMode = BackMode.Two
        exitMode = ExitMode.All
        initView()
        // 保持不息屏
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        // 初始化悬浮窗
        val floatWindow = MainFloatViewWrapper(applicationContext)
        floatWindow.show()
        // 悬浮窗设置改变
        Conf.getConf().setFlowSettingChanged { if(it!!){floatWindow.show()}else{floatWindow.hide()} }
        // 用户今日未签到则跳转签到页
        if(!GlobalData.user!!.signIn){
            startActivity(Intent(this, SignInActivity::class.java))
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        (viewPage.adapter as TabFragmentAdapter).fileFragment.refreshScriptList()
        settingDialog
    }

    /**
     * 初始化
     */
    private fun initView() {
        // 初始化设置弹窗
        settingDialog = SettingDialog(this)
        // 检测无障碍服务
        CommonUtils.toastDialog(this,title="需要启用无障碍服务", cancelable = false,
            content = "脚本需要使用无障碍服务来开启模拟点击，请在打开设置后，找到\"风珝游戏脚本\"选项后开启。 ",
            onPositive = {startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))})
        // 设置viewPage适配器
        viewPage.adapter = TabFragmentAdapter(supportFragmentManager)
        // 从xml中读取tab标题
        var tabArray = resources.getTextArray(R.array.tabArr)
        // 添加tabBar
        var tabSegment = findViewById<TabSegment>(R.id.tabSegment)
        for (tab in tabArray) {
            tabSegment.addTab(TabSegment.Tab(tab))
        }
        tabSegment.setupWithViewPager(viewPage, false)
        tabSegment.mode = TabSegment.MODE_FIXED
        viewPage.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ):Unit = Unit
            override fun onPageSelected(position: Int) {
                tabSelectChangeEvents.forEach { it.invoke(position) }
            }
            override fun onPageScrollStateChanged(state: Int):Unit = Unit

        })
        viewPage.offscreenPageLimit = tabArray.size

        // 添加点击更多出现设置弹窗
        findViewById<ImageButton>(R.id.actionbar_more).onClick {
            settingDialog.show()
        }

        // 打开日志页
        findViewById<ImageButton>(R.id.actionbar_log).onClick {
            startActivity(Intent(this@MainActivity, LoggerActivity::class.java))
        }

        // 创建脚本文件夹
        initFileEnv()
    }

    // 监听用户按下按键
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyDownListener.any { it.invoke(keyCode)  }){
            return true
        }else{
            return super.onKeyDown(keyCode, event)
        }
    }

    // 开始触摸时的x坐标
    private var startX = 0F;
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        when(ev!!.action ){
            MotionEvent.ACTION_DOWN -> startX = ev.x
            MotionEvent.ACTION_UP -> {
                if(startX < 100 && ev.x - startX >= 250 && viewPage.currentItem == 0){
                    // 向右滑动指定距离且为第一页时，显示设置弹窗
                    settingDialog.show()
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 初始化脚本的文件夹环境
     */
    private fun initFileEnv(){
        var externalFilesDir = getExternalFilesDir(null)
        val scriptFolder = File(externalFilesDir!!.path + "/" + GlobalData.MusicScriptFolderName)
        if(!scriptFolder.exists()){
            scriptFolder.mkdir()
        }
        GlobalData.MusicScriptFolderPath = scriptFolder.path
        // 文件夹内没有文件时，复制教程文档至文件夹内
        if(scriptFolder.listFiles().isEmpty()){
            assets.list("script")!!.forEach {
                val file = File(scriptFolder.path + "/${it}")
                file.createNewFile()
                assets.open("script/${it}").copyTo(file.outputStream())
            }
        }
    }

    override fun onDestroy() {
        AutoAccessibilityService.accessibilityService?.disableSelf()
        stopService(Intent(this, SafeService::class.java))
        super.onDestroy()
    }

}